package cate.game.server.configuration;

import cate.game.GameBody;
import cate.game.ManyGame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.stereotype.Component;

// 通过使用ConfigurableApplicationContext接口上的close（）方法关闭ApplicationContext时发布。
// 在此，“封闭”表示所有单例豆都被破坏。封闭的情境到了生命的尽头。无法刷新或重新启动。
@Slf4j
@Component
public class AppClosedListener implements ApplicationListener<ContextClosedEvent> {

    private ManyGame games;
    @Autowired
    public void setGames(ManyGame games) {
        this.games = games;
    }

    @Override
    public void onApplicationEvent(ContextClosedEvent event) {
        log.info("监听 ContextClosedEvent = {}", event);
        for(GameBody game : games.getAll()) {
            game.shutdown();
        }
    }
}
